import {Form, Modal, Radio, Table, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
import {isSuccess} from "@/utils/utils";
import {DesignerManager} from "@/services/api-functions";
import {AUDIT_QUERY_PARAM_VALUE, SYS_ENUMS} from "@/utils/constants";

export interface ResourceListProps {
  type: 'CUSTOMIZE' | 'CREATE'
  handleDesignerAudit: Function
}


const ApplyDesignerList: React.FC<ResourceListProps> = ({type, handleDesignerAudit}) => {

  const [auditFormRef] = Form.useForm()
  const [auditState, setAuditState] = useState<'ALL' | 'ING' | 'PASS' | 'REFUSE'>('ING');
  const [countInfo, setCountInfo] = useState<{ all: number, ing: number, pass: number, refuse: number }>({
    all: 0,
    ing: 0,
    pass: 0,
    refuse: 0
  });
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [preview, setPreview] = useState<0 | 1 | 2>(0)
  const customColumns: ProColumns[] = [
    {
      title: '当前星级',
      dataIndex: 'customizeLevel',
      valueEnum: SYS_ENUMS.LEVEL,
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '申请星级',
      dataIndex: 'designerQueryType',
      valueEnum: SYS_ENUMS.LEVEL,
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '申请星级',
      dataIndex: 'customizeLevel',
      valueEnum: SYS_ENUMS.LEVEL,
      ellipsis: true,
      hideInTable: true,
      width: 120,
    }
  ];
  const createColumns: ProColumns[] = [
      {
        title: '申请类别',
        dataIndex: 'registrationAdded',
        valueEnum: SYS_ENUMS.DESIGN_TYPE,
        ellipsis: true,
        hideInTable: true,
      },
    {
      title: '申请类别',
      dataIndex: 'registrationAdded',
      valueEnum: SYS_ENUMS.DESIGN_TYPE,
      ellipsis: true,
      hideInSearch: true,
      width: 270,
      render: (dom, entity) => entity.registrationAdded ? entity.registrationAdded.map((code: string) =>
        // eslint-disable-next-line react/jsx-key
        <Tag color='blue'>{SYS_ENUMS.DESIGN_TYPE[code].text}</Tag>) : null
    }
];
  const columns: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'realName',
      ellipsis: true,
      width: 120,
      fixed: 'left'
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      ellipsis: true,
      width: 120,
    },
    {
      title: '申请状态',
      dataIndex: 'verified',
      valueEnum: SYS_ENUMS.APPLY_STATE,
      hideInSearch: true,
      width: 100,
    },
    ...(type==="CUSTOMIZE"?customColumns:createColumns),
    {
      title: '申请理由',
      dataIndex: 'reason',
      ellipsis: true,
      hideInSearch: true,
      width: 270,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTimeRange',
      hideInTable: true,
      valueType: 'dateTimeRange',
    },
    {
      title: '案例图片',
      dataIndex: ['worksAdded', 'demoAdd'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
      render: (_, record) => record?.worksAdded?.worksAdded ? <a key="edit" onClick={() => {
        setCurrentRow(record)
        setPreview(1)
      }}>下载</a> : '-'
    },
    {
      title: '作品集',
      dataIndex: 'worksAdded',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
      render: (_, record) => record?.worksAdded?.worksAdded ? <a key="edit" onClick={() => {
        setCurrentRow(record)
        setPreview(2)
      }}>下载</a> : '-'
    },
    {
      title: '申请时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        (record?.verified === SYS_ENUMS.APPLY_STATE.ADDED.value || record?.verified === SYS_ENUMS.APPLY_STATE.FIRST_APPLY.value) ?
          <a key="edit" onClick={() => {
            setCurrentRow(record)
            handleAuditVisible(true)
          }}>审核</a> : <span style={{color: 'gray'}}>审核</span>,
      ],
    },
  ];
  return (
    <>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={auditState} onChange={(e) => {
          setAuditState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.all ?? 0}</Radio.Button>
          <Radio.Button value='ING'>待审核 {countInfo?.ing ?? 0}</Radio.Button>
          <Radio.Button value='PASS'>已通过 {countInfo?.pass ?? 0}</Radio.Button>
          <Radio.Button value='REFUSE'>未通过 {countInfo?.refuse ?? 0}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {

          try {
            const res = await DesignerManager.approvedListCountInfo(type);

            if (isSuccess(res.code)) {
              setCountInfo(res.data)
            }
          } catch (e) {
            console.error(e)
          }

          const query = {...params, designerQueryType: type}
          if (auditState !== 'ALL') {
            query.verified = AUDIT_QUERY_PARAM_VALUE[auditState]
          }

          if(params.applyTimeRange){
            query.startTime = query.applyTimeRange[0]
            query.endTime = query.applyTimeRange[1]
            delete query.applyTimeRange
          }

          const {data: {data, total}, code}: any = await DesignerManager.approvedList(query);

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />

      <ModalForm
        title={`审核【${currentRow?.realName}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleDesignerAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.label, value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
      <Modal width={750} title={`查看${preview === 1 ? '案例' : '作品'}`} visible={preview != 0 && currentRow} onCancel={() => {
        setPreview(0);
        setCurrentRow(undefined)
      }}>
        <Table
          dataSource={(preview === 1 ? currentRow?.worksAdded?.demoAdd : [currentRow?.worksAdded?.worksAdded]) ?? []}
          columns={[
            {
              title: '序号',
              dataIndex: 'index',
              ellipsis: true,
              width: 100,
              render: (_, record, index) => index + 1,
            },
            {
              title: '封面',
              dataIndex: 'url',
              width: 200,
              render: (dom, record) => record.cover ? <img src={record?.url} alt={record.name} height={40}/> : '--'
            },
            {
              title: '名称',
              dataIndex: 'name',
              ellipsis: true,
            },
            {
              title: '操作',
              dataIndex: 'option',
              render: (_, record) => <a key={record?.key} href={record?.url} target='_blank' rel="noreferrer">下载</a>,
            },
          ]}/>
      </Modal>
    </>
  );
};

export default ApplyDesignerList;
